<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Exception;
use App\Common\Common;
use App\Models\CouponType;
use App\Jobs\SyncSendSms;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use App\Models\OrderPingan;

class CardController extends Controller
{
    function getCard(Request $request)
    {
        $onlys = [
            'token', 'price', 'mobile', 'card_type',
            'order_unicompay', 'usr_prov', 'usr_city'
        ];
        $musts = [
            'token', 'price', 'mobile', 'card_type',
            'order_unicompay'
        ];
        $inputs = $request->only($onlys);

        if (!$request->has($musts)) {
            return response()->json([
                'success' => false,
                'result_message' => 'some parameters is null!',
            ]);
        }

        try {
            $devId = $this->CheckDeveloperAccessToken($inputs);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'result_message' => $e->getMessage(),
            ]);
        }
        $pingan_card_types = [
            [
                'card_type' => 'HSH_SX01',
                'price' => 15.2,
                'provider' => 'pingan',
                'packageId' => 1
            ], [
                'card_type' => 'HSH_SX02',
                'price' => 21.2,
                'provider' => 'pingan',
                'packageId' => 2
            ],
            [
                'card_type' => 'HSH_SX03',
                'price' => 24.7,
                'provider' => 'pingan',
                'packageId' => 3
            ],
            [
                'card_type' => 'HSH_SX04',
                'price' => 33.7,
                'provider' => 'pingan',
                'packageId' => 4
            ]
        ];
        $result = [
            'success' => false,
            'result_message' => '接口调用失败，请联系管理！'
        ];
        foreach ($pingan_card_types as $pingan_card_type) {
            if ($pingan_card_type['card_type'] == $inputs['card_type']) {
                $inputs['price'] = $pingan_card_type['price'];
                if ($pingan_card_type['provider'] == "pingan") {
                    // 调用平安的接口
                    $result = $this->postPinganExchange([
                        'serialNumber' => $inputs['order_unicompay'],
                        'mobile' => $inputs['mobile'],
                        'packageId' => $pingan_card_type['packageId'],
                        'price' => $pingan_card_type['price'],
                    ], $devId);
                } else if ($pingan_card_type['provider'] == "suning") {
                    // 调用苏宁的接口
                    $result = $this->postSuningExchange($inputs, $devId);
                }
            }
        }
        return response()->json($result);
    }

    function reverseOrder(Request $request)
    {
        $onlys = [
            'token', 'order_unicompay'
        ];
        $musts = [
            'token', 'order_unicompay'
        ];
        $inputs = $request->only($onlys);

        if (!$request->has($musts)) {
            return response()->json([
                'success' => false,
                'result_message' => 'some parameters is null!',
            ]);
        }

        try {
            $this->CheckDeveloperAccessToken($inputs);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'result_message' => $e->getMessage(),
            ]);
        }

        $coupon = Coupon::where("allot_order_unicompay", $inputs['order_unicompay'])->first();
        if (!$coupon) {
            return response()->json([
                'success' => true,
                'result_message' => '成功',
            ]);
        } else {
            return response()->json([
                'success' => false,
                'result_message' => '失败'
            ]);
        }
    }

    function getPwd(Request $request)
    {
        $onlys = [
            'token', 'order_card'
        ];
        $musts = [
            'token', 'order_card'
        ];
        $inputs = $request->only($onlys);

        if (!$request->has($musts)) {
            return response()->json([
                'success' => false,
                'result_message' => 'some parameters is null!',
            ]);
        }

        try {
            $this->CheckDeveloperAccessToken($inputs);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'result_message' => $e->getMessage(),
            ]);
        }

        $coupon = Coupon::where("allot_serial_number", $inputs['order_card'])->first();
        if (!$coupon) {
            return response()->json([
                'success' => false,
                'result_message' => 'order_card does not exist!',
            ]);
        }

        return response()->json([
            'success' => true,
            'result_message' => '',
            'card_paw' => Common::AesEncode($coupon->code, config('app.client_secret'))
        ]);
    }

    /**
     * 调用平安的接口，提交exchange数据
     */
    protected function postPinganExchange($deal, $devId)
    {
        $fullUrl = config('app.pingan.url');
        $data = [
            'merchantId' => config('app.pingan.merchantId'),
            'merchantSerialNumber' => $deal['serialNumber'],
            'nonce_str' => config('app.pingan.nonce_str'),
            'packageId' => $deal['packageId'],
            'phoneNumber' => $deal['mobile'],
        ];

        //写入数据库
        OrderPingan::create([
            'serial_number' => $deal['serialNumber'],
            'phone_number' => $deal['mobile'],
            'package_id' => $deal['packageId'],
            'price' =>  $deal['price']
        ]);

        $sidnData = Arr::add($data, 'key', config('app.pingan.secretKey'));
        $sign = Str::upper(md5(http_build_query($sidnData)));
        $data = Arr::add($data, 'sign', $sign);
        Log::info(json_encode($data));
        $client = new Client();
        $response = $client->request('POST', $fullUrl, [
            'form_params' => $data,
            'timeout' => 5
        ]);
        $resp_status = $response->getStatusCode();
        if ($resp_status == 200) {
            $resp_content = $response->getBody()->getContents();
            Log::info($resp_content);
            $reqData = json_decode($resp_content, true);
            if ($reqData && json_last_error() == JSON_ERROR_NONE && isset($reqData['code']) && $reqData['code'] == 1000) {
                $content = '【欢生活】恭喜您获得了平安权益礼包，请您用办理业务的手机号登录链接http://ltpa.boruankeji.net/index.html，领取权益产品和填写保单。回复T退订';
                SyncSendSms::dispatch('pingan', $deal['mobile'], $content, []);

                return [
                    'success' => true,
                    'result_message' => '',
                    'order_card' => $deal['serialNumber'],
                    'card_id' => $deal['serialNumber'],
                    'card_paw' => Common::AesEncode($deal['serialNumber'], config('app.client_secret')),
                    'price' => $deal['price']
                ];
            }
        }
        return [
            'success' => false,
            'result_message' => '接口调用失败，请联系管理！'
        ];
    }

    protected function postSuningExchange($inputs, $devId) {
        $card_type = $inputs['card_type'];
        $couponType = CouponType::where('code', $card_type)->first();
        if (!$couponType) {
            return [
                'success' => false,
                'result_message' => 'card_type is error!',
            ];
        }

        $serial_number = date("ymdHis") . Str::random(12);
        $coupon = Coupon::where("status", 0)
            ->where("card_type", $card_type)
            ->orderBy('id')->first();

        if (!$coupon) {
            // TODO: 如果卡池没有卡了，是生成新卡，还是？
            return [
                'success' => false,
                'result_message' => 'the card is null.'
            ];
        }
        $now = time();
        switch ($coupon->valid_type) {
            case 2:
                $valid_data = date("Y-m-d", $now + 3600 * 24 * 61);
                break;
            case 3:
                $valid_data = date("Y-m-d", $now + 3600 * 24 * 366);
                break;
            default:
                $valid_data = date("Y-m-d", $now + 3600 * 24 * 31);
        }

        $coupon->status = 1;
        $coupon->valid_dates = $valid_data;
        $coupon->allot_serial_number = $serial_number;
        $coupon->allot_time = date("Y-m-d H:i:s", $now);
        $coupon->allot_developer_id = $devId;
        $coupon->allot_order_unicompay = $inputs['order_unicompay'];
        $coupon->accepter_phone = $inputs['mobile'];
        $coupon->allot_ext_info = json_encode([
            'usr_prov' => isset($inputs['usr_prov']) ? $inputs['usr_prov'] : "",
            'usr_city' => isset($inputs['usr_city']) ? $inputs['usr_city'] : ""
        ]);
        $coupon->save();

        // 发送短信给用户
        $content = '【欢生活】尊敬的用户，您获得了一张家政服务抵用券，点链接 ' . config('app.url') . ' 使用。回复T退订';
        SyncSendSms::dispatch('card', $inputs['mobile'], $content, [
            'card_id' => $coupon->code,
            'allot_serial_number' => $serial_number
        ]);

        return [
            'success' => true,
            'result_message' => '',
            'order_card' => $serial_number,
            'card_id' => $coupon->code,
            'card_paw' => Common::AesEncode($coupon->code, config('app.client_secret')),
            'price' => $coupon->price
        ];
    }
}
